package com.qingfeng.client.service;

import com.qingfeng.client.bean.Trade;
import com.qingfeng.client.bean.TradeQueueMsg;
import com.qingfeng.client.util.TradeEnum;
import com.qingfeng.util.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.DelayQueue;

/**
 * 用户未支付取消订单队列服务器
 * @author zhangyuefei
 * @version 1.0
 * @date 2020/1/9 5:41 下午
 */
@Slf4j
@Service
public class DealQueueService {

    //取消支付延迟时间，单位毫秒
    @Value("${canclePayExpire}")
    private long expire;

    @Autowired
    private OrderService orderService;

    //订单的队列
    public static DelayQueue<TradeQueueMsg> overQueue= new DelayQueue<TradeQueueMsg>();

    public void initQueue(){
        log.info("初始化订单取消队列");
        List<Trade> list = orderService.getAllByTradeStat(TradeEnum.TRADE_WAIT_PAY);
        for (Trade trade:list){
            add(trade);
        }
    }


    /**
     * 添加交易信息至队列
     * @param trade
     */
    public void add(Trade trade){
        TradeQueueMsg tradeQueueMsg = new TradeQueueMsg();
        //如果支付超时时间，在现在之前，则直接假如队列中
        if ((trade.getCreateTime()*1000L + expire)<System.currentTimeMillis()){
            tradeQueueMsg.setExpiredTime(System.currentTimeMillis()+1000);
        }else {
            tradeQueueMsg.setExpiredTime(trade.getCreateTime() * 1000L + expire);
        }
        tradeQueueMsg.setTradeId(trade.getId());
        overQueue.add(tradeQueueMsg);
    }

    public void startDealQueue(){
        new Thread(){
            @Override
            public void run() {
                System.out.println("=============开启订单处理线程===========");
                while (true){
                    TradeQueueMsg queueMsg = null;
                    try {
                        // 没有满足延时的元素 用poll返回 null
                        // 没有满足延时的元素 用take会阻塞
                        queueMsg =  overQueue.take();
                        if (queueMsg.getTradeId()!=null){
                            orderService.canclePay(queueMsg.getTradeId());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }.start();
    }


}
